<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/12/8
 * Time: 10:27
 */

namespace app\api\controller;

use app\admin\model\Apply;
use app\admin\model\BydAgreement;
use app\admin\model\BydBusiness;
use app\admin\model\BydDesfollow;
use app\admin\model\BydDesigner;
use app\admin\model\BydDesignerArea;
use app\admin\model\BydDestri;
use app\admin\model\BydForm;
use app\admin\model\Bydletter;
use app\admin\model\BydShopActivity;
use app\admin\model\BydShopOrder;
use app\admin\model\BydUserAg;
use app\admin\model\BydUsercupons;
use app\admin\model\BydUserSale;
use app\admin\model\ShopOrder;
use app\admin\model\SoleBuilding;
use app\admin\model\Sorce;
use app\admin\model\Temrela;
use app\admin\model\Twotg;
use think\Cache;
use app\common\controller\News;
use app\admin\model\BydDesignerMake;
use app\admin\model\BydDistri;
use app\common\controller\Api;
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");
class BydUser extends Api
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = ['*'];
    /**
     * 编辑资料
     * * @param integer $id 用户id
     * @param integer $birthday 生日
     * @param integer $nickname 昵称
     * @param integer $email 邮箱
     * @param integer $avatar 头像
     * @param integer $qian 个性签名
     */
    public function edituser(){
        $request=request();
        $data=$request->param();
        if(!empty($data['avatar'])){
            $data['avatar']= preg_replace("/\/uploads\//",'https://bao.scwushen.com/uploads/', $data['avatar'] );
        }
        $save=new \app\admin\model\BydUser();
        $where['id']=$data['id'];

        $edit=$save->isUpdate(true,$where)->save($data);
        if($edit){
            $user=\app\admin\model\BydUser::find($data['id']);
            $this->success(__('修改成功'),['status'=>$user]);
        }else{
            $this->error('修改失败');
        }
//        if ($user) {
//            $this->success(__('修改成功'));
//            return $user;
//        } else {
//            $this->error('修改失败');
//            return null;
//        }
//        if($cre==null){
//            $this->error('修改失败');
//        }else{
//            $this->success(__('修改成功'));
//        }
    }
    /**
     * 个人资料
     *@param integer $user_id` '用户id',
     */
    public function myuser(){
        $request=request();
        $data=$request->param();
        if (empty($data['user_id']))$this->error('请传参数');
        $find=\app\admin\model\BydUser::find($data['user_id']);
        $where['user_id']=$data['user_id'];
        $where['state']=1;
        $where['usetime']=null;
        $find['coupnum']=BydUsercupons::where($where)->count();
        if($find['bbs']==0){
            $find['bbs']=[
                'typesk'=>'yiji',
                'type'=>'馨级美居会员'
            ];
        }else{
            $find['bbs']=\app\admin\model\BydIden::find($find['bbs']);//BydIdentity  2022-04-20
        }
        $open=BydBusiness::where('id',2)->find();
        if($open['switch']==1){
            $find['edit']=true;

        }else{
            $find['edit']=false;
        }
        $find['jifen']=true;
        if($find){
            $this->success(__('请求成功'),['myuser'=>$find]);
        }else{
            $this->error('请求失败');
        }
    }
    /**
     * 添加或修改地址
     * @param integer $user_id` '用户id',
     * @param integer $username` '姓名',
     * @param integer $phone` '电话',
     * @param integer $title` '地址',
     * @param integer $address` '详细地址',
     * @param integer $auto` '0为修改1为添加',
     * @param integer $type` '0为修改1为添加',
     *  user_id  用户id
     *    username姓名
     *    phone电话
     *   title地址
     * address 详细地址
     *   auto 0为修改1为添加
     *   type0为修改1为添加
     */
    public function address(){
        $request=request();
        $data=$request->param();
        $user=new \app\api\model\BydUser();
        $address=$user->address($data);
        if($address==null){
            $this->error('请求失败');
        }else{
            $this->success(__('请求成功'));
        }
    }

    /**
     * 删除地址
     * @param integer $user_id` '用户id',
     * @param integer $auto` '是否为默认',
     *  @param user_id  用户id
     *  @param id id
     *  
     */
    public function addressdel(){
        $request=request();
        $data=$request->param();
        $res = 0;
        if($data['userid'] > 0 && $data['id'] > 0)
        {
            $where = ['userid'=>$data['userid'], 'id'=>$data['id']];
            $data = \app\admin\model\BydAddress::where($where)->find();
            $res = \app\admin\model\BydAddress::where($where)->delete();
            if($data['auto']==1)
            {
                $data2 = \app\admin\model\BydAddress::where(['userid'=>$data['userid']])->find();
                if(!empty($data2))
                {                 
                    $res=\app\admin\model\BydAddress::update(['auto'=>1],['id'=>$data2['id']]);  
                }
            }
        }
        if($res){
            $this->success(__('请求成功'));
        }else{
            $this->error('请求失败');
        }
    }
    /**
     * 地址列表
     * * @param integer $id` '用户id',

     */
   public function addressshow(){
       $request=request();
       $data=$request->param();
       if(empty($data['id'])) $this->error('参数错误');
       $user=\app\admin\model\BydUser::find($data['id']);
       if(empty($user))$this->error('用户信息错误');
       $all=\app\api\model\BydUser::addressshow($data);
       if($all==null){
           $this->error('暂无数据');
       }else{
           $this->success(__('请求成功'),['status'=>$all]);
       }
   }
   /**
    * 我的收藏
    * @param integer $user_id` '用户id',
    * @param integer $type` '0为商品1为视频',
    * user_id  用户id
    * type 0为商品1为视频
    */
   public function myfollow(){
       $request=request();
       $data=$request->param();
       $all=\app\api\model\BydShop::lookfollow($data);
       if($all==null){
           $this->error('暂无数据');
       }else{
           $this->success(__('请求成功'),['status'=>$all]);
       }
   }
    /**
     * 删除收藏
     * @param integer $id` '收藏的id',
     */
    public function delfollow(){
        $data= $this->request->request('');
        $del=\app\admin\model\BydMyfollow::where('id',$data['id'])->delete();
        if($del){
            $this->success(__('请求成功'));
        }else{
            $this->error('请求失败');
        }
    }
    /**
     * 积分明细
     */
    public function sorcemx(){
        $data= $this->request->request('');
        if(empty($data['user_id'])) $this->error('暂无数据');
        $user=\app\admin\model\BydUser::find($data['user_id']);
        if(empty($user)) $this->error('用户信息错误');
        $arr=Sorce::where('user_id',$data['user_id'])->order('id desc')->paginate(20);
        if(empty($arr))$this->error('暂无数据');
        $this->success(__('请求成功'),['status'=>$arr]);
    }
   /**
    * 我的预约记录
    * @param integer $user_id` '用户id',
    * @param integer $lilmit` '分页条数',
    * user_id  用户id
    *  lilmit
    */
    public function mymake(){

        $request=request();
        $data=$request->param();

        $arr=BydDesignerMake::where('user_id',$data['user_id'])->paginate($data['limit']);
        $dis=BydDistri::where('user_id',$data['user_id'])->find();
        if (!empty($dis)){
            if($dis['pid']>0){
                $xbh=BydUserSale::where('user_id',$dis['pid'])->find();
                $xsbh=$xbh['bh'];
            }else{
                $xsbh=0;
            }

        }else{
            $xsbh=0;
        }
        foreach ($arr as &$v){
            $user=\app\api\model\BydUser::where('id',$v['user_id'])->field('bh')->find();
             $v['xsbh']=$xsbh;
            $v['desbh']=BydDesigner::where('id',$v['des_id'])->field('bh')->find();
            $v['userbh']=$user['bh'];
            $v['statess']=BydShopOrder::where('yyid',$v['orderid'])->find();//同步订单的状态
        }
        if($arr){

            $this->success(__('请求成功'),['status'=>$arr]);
        }else{
            $this->error('暂无数据');
        }
    }
    /**
     * 微信登录
     *  * @param integer $code` '前端提交的code',
     * @param integer $iv` '前端提交的iv',
     * @param integer $encrypteData` '前端提交的encrypteData',
     * @param  $code
     * @param  $iv
     * @param  $encrypteData
     */
    public function wxlogin(){

        $data = $this->request->request('');
        $param['appid'] = 'wx00e9e5b843259a9d';    //小程序id
        $param['secret'] = '5a47f8a3b97773614c77da7900a896a3';    //小程序密钥
        $param['js_code'] = str_replace(' ','+',$data['code']);
        $param['grant_type'] = 'authorization_code';
        function httpCurl($url, $params, $method = 'POST', $header = array(), $multi = false){
            date_default_timezone_set('PRC');
            $opts = array(
                CURLOPT_TIMEOUT        => 30,
                CURLOPT_RETURNTRANSFER => 1,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_HTTPHEADER     => $header,
                CURLOPT_COOKIESESSION  => true,
                CURLOPT_FOLLOWLOCATION => 1,
                CURLOPT_COOKIE         =>session_name().'='.session_id(),
            );
            /* 根据请求类型设置特定参数 */
            switch(strtoupper($method)){
                case 'GET':
                    // $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                    // 链接后拼接参数  &  非？
                    $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                    break;
                case 'POST':
                    //判断是否传输文件
                    $params = $multi ? $params : http_build_query($params);
                    $opts[CURLOPT_URL] = $url;
                    $opts[CURLOPT_POST] = 1;
                    $opts[CURLOPT_POSTFIELDS] = $params;
                    break;
                default:
                    throw new Exception('不支持的请求方式！');
            }
            /* 初始化并执行curl请求 */
            $ch = curl_init();
            curl_setopt_array($ch, $opts);
            $data  = curl_exec($ch);
            $error = curl_error($ch);
            curl_close($ch);
            if($error) throw new Exception('请求发生错误：' . $error);
            return  $data;
        }


        $http_key = httpCurl('https://api.weixin.qq.com/sns/jscode2session', $param, 'GET');
        $session_key = json_decode($http_key,true);
        // $this->success(__('请求成功'), ['status' => $session_key]);
        //print_r(http_build_query($param));
        if (!empty($session_key['session_key'])) {
            $appid = $param['appid'];
            $encrypteData = $data['encryptedData'];
            $iv = str_replace(' ','+',$data['iv']);
            function decryptData( $appid , $sessionKey, $encryptedData, $iv ){
                $OK = 0;
                $IllegalAesKey = -41001;
                $IllegalIv = -41002;
                $IllegalBuffer = -41003;
                $DecodeBase64Error = -41004;
                if (strlen($sessionKey) != 24) {
                    return $IllegalAesKey;
                }
                $aesKey=base64_decode($sessionKey);

                if (strlen($iv) != 24) {
                    return $IllegalIv;
                }
                $aesIV=base64_decode($iv);
                $aesCipher=base64_decode($encryptedData);
                $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
                $dataObj=json_decode( $result );
                if( $dataObj  == NULL )
                {
                    return $IllegalBuffer;
                }
                if( $dataObj->watermark->appid != $appid )
                {
                    return $DecodeBase64Error;
                }
                $data = json_decode($result,true);
                return $data;
            }

            $errCode = decryptData($appid, $session_key['session_key'], $encrypteData, $iv);

            //$errCodes = $this->decryptDatas($appid, $session_key['session_key'], $encrypteData, $iv, $data);
            //$errCode = json_decode($errCodee,true);
            //$this->success(__('添加成功'), ['status' => dump($errCode)]);
            //把appid写入到数据库中
//                if ($errCodes == 0) {
//
//                 print_r($data);die;
//
//                    }

//            $creatt['username'] = $errCode['nickName'];
//            $creatt['avatar'] = $errCode['avatarUrl'];
//            $creatt['gender'] = $errCode['gender'];
//            $creatt['openid'] = $session_key['openid'];
            $creatt['pid'] = $data['pid'];
            $user=new \app\admin\model\BydUser();
            $where['openid']=$session_key['openid'];
            $find=$user->where($where)->find();
            if($find){
                if ($data['pid']>0 && $data['level']>0){
                    if($data['level']<4){
                        $bbs=BydDistri::where('user_id',$data['pid'])->find();//查看拉新人的身份
                        $disfind=BydDistri::where('user_id',$find['id'])->find();//查看是否有上级

                        if(!empty($bbs) && empty($disfind)){
                            if($bbs['family']>0){
                                //bs拉新
                                $add = new BydDistri();
                                $add->data([
                                    'family'  => $bbs['pid'],//$bbs['family']
                                    'pid' =>  $data['pid'],
                                    'user_id' =>  $find['id'],
                                    'level' =>  $data['level']
                                ]);
                                $add->save();
                            }else{
                                //b1
                                $add = new BydDistri();
                                $add->data([
                                    'family'  => $data['pid'],
                                    'pid' =>  $data['pid'],
                                    'user_id' =>  $find['id'],
                                    'level' =>  $data['level']
                                ]);
                                $add->save();
                            }
                        }
                    }else{
                        $des=BydDestri::where('user_id',$data['pid'])->find();//查看拉新人的身份
                        $disfind=BydDestri::where('user_id',$find['id'])->find();//查看是否有上级
                        if(!empty($des) && empty($disfind)){
                            if($des['family']>0){
                                //d1拉新
                                $add = new BydDestri();
                                $add->data([
                                    'family'  => $des['family'],
                                    'pid' =>  $data['pid'],
                                    'user_id' =>  $find['id'],
                                    'level' =>  $data['level']
                                ]);
                                $add->save();
                            }else{
                                //d2
                                $add = new BydDestri();
                                $add->data([
                                    'family'  => $data['pid'],
                                    'pid' =>  $data['pid'],
                                    'user_id' =>  $find['id'],
                                    'level' =>  $data['level']
                                ]);
                                $add->save();
                            }
                        }
                    }
                }else{
                    if($data['pid']>0){

                        $puser=\app\admin\model\BydUser::find($data['pid']);

                        if(!empty($puser)){
                            $piddis=BydDistri::where('user_id',$data['pid'])->find();
                            if($piddis){
                                //查看pid身份
                                $shenfen=\app\admin\model\BydUser::find($piddis['pid']);

                                if($shenfen){
//                            print_r($piddis['pid']);die;
                                    if($shenfen['bbs']==0){
//                                echo 111;die;
                                        $add = new BydDistri();
                                        $add->data([
                                            'family'  => $piddis['family'],
                                            'pid' =>  $data['pid'],
                                            'user_id' =>  $find['id'],
                                            'level' =>  $data['level']
                                        ]);
                                        $add->save();
                                    }else{
                                        $add = new BydDistri();
                                        $add->data([
                                            'family'  => $piddis['pid'],
                                            'pid' =>  $data['pid'],
                                            'user_id' =>  $find['id'],
                                            'level' =>  $data['level']
                                        ]);
                                        $add->save();
                                    }
                                }
                            }else{
                                //c拉c
                                if($puser['bbs']==0){
                                    $add = new BydDistri();
                                    $add->data([
                                        'family'  => 0,
                                        'pid' => 0,
                                        'user_id' =>  $data['pid'],
                                        'level' => 0
                                    ]);
                                    $add->save();
                                    $adds = new BydDistri();
                                    $adds->data([
                                        'family'  => $data['pid'],
                                        'pid' => $data['pid'],
                                        'user_id' => $find['id'],
                                        'level' => 0
                                    ]);
                                    $adds->save();
                                }
                            }
                        }
                    }
                }
//                if($find['bbs']>0){
//                    $level=\app\admin\model\BydIdentity::find($find['bbs']);
//                    $find['levelbs']=$level;
//                }else{
//                    $find['levelbs']=null;
//                }
//                if($data['pid']>0 && $data['level']>2) {
//                    $sux = BydDestri::where('user_id', $find['id'])->find();//设计师
//                }else{
//                    $sux = BydDistri::where('user_id', $find['id'])->find();//销售员
//                }
//                    if(empty($sux)){
//                        $level=\app\admin\model\BydIdentity::find($data['level']);
//                        if($data['level']==2 || $data['level']==4){
//                            $creatt['family']=$data['pid'];
//                        }else{
//                            $suxs=BydDistri::where('user_id',$data['pid'])->find();
//                            //$creatt['family']=$suxs['family'];
//                        }
//                        $add = new BydDistri();
//                        $add->data([
//                            'family'  => $creatt['family'],
//                            'pid' =>  $data['pid'],
//                            'user_id' =>  $find['id'],
//                            'level' =>  $data['level']
//                        ]);
//                        $add->save();
//                    }

                $loginToken = md5(date('YmdHis' . $find['id']));//存入缓
                Cache::set($loginToken, $find['id'], 7200*12);
                $edit= $user->isUpdate(true,['id'=>$find['id']])->save(['token'=>$loginToken]);
				if(@fopen($find['avatar'],"r")){ 
				}else{ 
					$find['avatar'] = 'https://bao.scwushen.com/'.$find['avatar'];
				}
				$find['key']=$session_key['session_key'];
                $this->success(__('请求成功'), ['status' => $find,'token'=>$find['token']]  );
            }else{
//                $user = new Byd($errCode);
//// 过滤post数组中的非数据表字段数据
//                $user->allowField(true)->save();
                $cre = new \app\api\model\BydUser();
                $cre->data([
                    'username'  => $errCode['nickName'],
                    'avatar' =>  $errCode['avatarUrl'],
                    'gender' =>  $errCode['gender'],
                    'openid' =>  $session_key['openid'],
                    'bh'=>"C-" .  str_pad(rand(1,9999), 5, '0',  STR_PAD_LEFT),
                        'pid' =>  $data['pid']
                ]);
                $cre->save();
               // $cre=$user->insert($creatt);
                if($cre){
                    // $uid = $this->db->id();
                    //cacheRedis()->set($loginToken, $uid, 7200*12);
                    $where['openid']=$session_key['openid'];
                    $finds=$user->where($where)->find();
                    $finds['key']=$session_key['session_key'];
                    if ($data['pid']>0 && $data['level']>0){
                        if($data['level']<3){
                            $bbs=BydDistri::where('user_id',$data['pid'])->find();//查看拉新人的身份
                            $disfind=BydDistri::where('user_id',$finds['id'])->find();//查看是否有上级

                            if(!empty($bbs) && empty($disfind)){
                                if($bbs['family']>0){
                                    //bs拉新
                                    $add = new BydDistri();
                                    $add->data([
                                        'family'  => $bbs['family'],
                                        'pid' =>  $data['pid'],
                                        'user_id' =>  $finds['id'],
                                        'level' =>  $data['level']
                                    ]);
                                    $add->save();
                                }else{
                                    //b1
                                    $add = new BydDistri();
                                    $add->data([
                                        'family'  => $data['pid'],
                                        'pid' =>  $data['pid'],
                                        'user_id' =>  $finds['id'],
                                        'level' =>  $data['level']
                                    ]);
                                    $add->save();
                                }
                            }
                        }else{
                            $des=BydDestri::where('user_id',$data['pid'])->find();//查看拉新人的身份
                            $disfind=BydDestri::where('user_id',$finds['id'])->find();//查看是否有上级
                            if(!empty($des) && empty($disfind)){
                                if($des['family']>0){
                                    //d1拉新
                                    $add = new BydDestri();
                                    $add->data([
                                        'family'  => $des['family'],
                                        'pid' =>  $data['pid'],
                                        'user_id' =>  $finds['id'],
                                        'level' =>  $data['level']
                                    ]);
                                    $add->save();
                                }else{
                                    //d2
                                    $add = new BydDestri();
                                    $add->data([
                                        'family'  => $data['pid'],
                                        'pid' =>  $data['pid'],
                                        'user_id' =>  $finds['id'],
                                        'level' =>  $data['level']
                                    ]);
                                    $add->save();
                                }
                            }
                        }
                    }else{
                        if($data['pid']>0){

                            $puser=\app\admin\model\BydUser::find($data['pid']);

                            if(!empty($puser)){
                                $piddis=BydDistri::where('user_id',$data['pid'])->find();
                                if($piddis){
                                    //查看pid身份
                                    $shenfen=\app\admin\model\BydUser::find($piddis['pid']);

                                    if($shenfen){
//                            print_r($piddis['pid']);die;
                                        if($shenfen['bbs']==0){
//                                echo 111;die;
                                            $add = new BydDistri();
                                            $add->data([
                                                'family'  => $piddis['family'],
                                                'pid' =>  $data['pid'],
                                                'user_id' =>  $finds['id'],
                                                'level' =>  $data['level']
                                            ]);
                                            $add->save();
                                        }else{
                                            $add = new BydDistri();
                                            $add->data([
                                                'family'  => $piddis['pid'],
                                                'pid' =>  $data['pid'],
                                                'user_id' =>  $finds['id'],
                                                'level' =>  $data['level']
                                            ]);
                                            $add->save();
                                        }
                                    }
                                }else{
                                    //c拉c
                                    if($puser['bbs']==0){
                                        $add = new BydDistri();
                                        $add->data([
                                            'family'  => 0,
                                            'pid' => 0,
                                            'user_id' =>  $data['pid'],
                                            'level' => 0
                                        ]);
                                        $add->save();
                                        $adds = new BydDistri();
                                        $adds->data([
                                            'family'  => $data['pid'],
                                            'pid' => $data['pid'],
                                            'user_id' => $finds['id'],
                                            'level' => 0
                                        ]);
                                        $adds->save();
                                    }
                                }
                            }
                        }
                    }
                    $loginToken = md5(date('YmdHis' . $finds['id']));//存入缓
                    Cache::set($loginToken, $finds['id'], 7200*12);
                    $edit= $user->isUpdate(true,['id'=>$finds['id']])->save(['token'=>$loginToken]);

                    $this->success(__('请求成功'), ['status' => $finds,'token'=>$loginToken]);
                }else{
                    $this->error('添加失败', ['status' => '添加失败']);
                }
            }



//                $data['nicheng'] = $errCode['nickName'];
//                $data['publishtime'] = time();
//                $data['sex'] = $errCode['gender'];
//                if (false == Db::name('message_user')->where(['appid' => $data['appid']])->find()) {
//                    Db::name('message_user')->insert($data);
//                    $value = Db::name('message_user')->where(['appid' => $data['appid']])->field('appid,nicheng,publishtime,sex')->select();
//                }else{
//                    $value = Db::name('message_user')->where(['appid' => $data['appid']])->field('appid,nicheng,publishtime,sex')->select();
//                }
//                $array = array_merge_recursive($errCode, $value);
//                return json($array);
        }else{
            echo '获取session_key失败！';
        }
        // return json(['status' =>1]);
    }

    /**

     * 检验数据的真实性，并且获取解密后的明文.

     * @param $encryptedData string 加密的用户数据

     * @param $iv string 与用户数据一同返回的初始向量

     * @param $data string 解密后的原文

     *

     * @return int 成功0，失败返回对应的错误码

     */

    private function decryptDatas( $appid,$sessionKey,$encryptedData, $iv, &$data )

    {

        if (strlen($sessionKey) != 24) {

            return -41001;

        }

        $aesKey=base64_decode($sessionKey);

        if (strlen($iv) != 24) {

            return -41002;

        }

        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );

        if( $dataObj == NULL )

        {

            return -41003;

        }

        if( $dataObj->watermark->appid != $appid )

        {

            return -41004;

        }

        $data = $dataObj;

        return 0;

    }
    /**
     * 关注
     *  @param integer $user_id` '用户id',
     *  @param integer $tes_id` '设计师id',
     * 设计师tes_id
     * user_id
     */
    public  function desfollow(){
        $data = $this->request->request('');
        $foolow=BydDesfollow::where('user_id',$data['user_id'])->where('text_id',$data['tes_id'])->find();
        if($foolow){
            $del=BydDesfollow::where('user_id',$data['user_id'])->where('text_id',$data['tes_id'])->delete();
            if($del){
                $int=BydDesigner::where('id',$data['tes_id'])->setDec('follow',1);//关注人数+1
                $this->success(__('取消关注成功'));
            }else{
                $this->error('取消关注失败');
            }
        }else{
            $add=new BydDesfollow();
            $add->data([
                'user_id'  => $data['user_id'],
                'text_id' => $data['tes_id'],
            ]);
            $add->save();
            if($add){
                $int=BydDesigner::where('id',$data['tes_id'])->setInc('follow',1);//关注人数+1
                $this->success(__('关注成功'));
            }else{
                $this->error('关注失败');
            }
        }

    }
    /**
     * 我的关注
     * @param integer $user_id` '用户id',
     * @param integer $page` '页数',
     * @param integer $limit` '一页的条数',
     * page limit user_id
     */
    public function mydesigner(){
        $data = $this->request->request('');
        $arr=BydDesfollow::where('user_id',$data['user_id'])->paginate($data['limit']);
        if ($arr){
            foreach ($arr as &$v){
                $v['createtime']=date('Y-m-d H:i',$v['createtime']);
                $v['des']=BydDesigner::find($v['text_id']);
            }

            $this->success(__('请求成功'),['status' => $arr]);
        }else{
            $this->error('暂无数据');
        }
    }
    /**
     * 电子名片
     * @param integer $state` '0为销售员1为设计师',
     *  state 0为销售员1为设计师
     */
    public function business(){
        $data = $this->request->request('');
        $find=BydBusiness::where('state',$data['state'])->where('id',1)->find();
        if($find){
            $this->success(__('请求成功'),['status' => $find]);
        }else {
            $this->error('暂无数据');
        }
    }
    /**
     * 微信退款
     * @param  string   $order_id 	订单ID
     * @return 成功时返回(array类型)，其他抛异常
     */
    function wxRefund($order_id){
        //我的SDK放在项目根目录下的Api目录下
        require_once EXTEND_PATH."php_sdk_v3.0.10/lib/WxPay.Api.php";
        //查询订单,根据订单里边的数据进行退款
        $order = M('order')->where(array('id'=>$order_id,'is_refund'=>2,'order_status'=>1))->find();
        $merchid = \WxPayConfig::GetMerchantId();

        if(!$order) return false;

        $input = new \WxPayRefund();
        $input->SetOut_trade_no($order['order_sn']);			//自己的订单号
        $input->SetTransaction_id($order['transaction_id']);  	//微信官方生成的订单流水号，在支付成功中有返回
        $input->SetOut_refund_no(getrand_num(true));			//退款单号
        $input->SetTotal_fee($order['total_price']);			//订单标价金额，单位为分
        $input->SetRefund_fee($order['total_price']);			//退款总金额，订单总金额，单位为分，只能为整数
        $input->SetOp_user_id($merchid);

        $result = \WxPayApi::refund($input);	//退款操作

        // 这句file_put_contents是用来查看服务器返回的退款结果 测试完可以删除了
        //file_put_contents(APP_ROOT.'/Api/wxpay/logs/log3.txt',arrayToXml($result),FILE_APPEND);
        return $result;
    }
    /**
     * 单独传照片
     */
    public function addpostspic(){
        $data=$this->request->request('');
        $files = $this->request->file('image');
        if($files) {
            $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
            $save_path = '/uploads/';
            $infos = $files->move($upload_path);
            if ($infos) {
                $data['image'] = str_replace('\\', '/', $save_path . $infos->getSaveName());
            }
        }
//        $user = AllPicture::create([
//            'image'  =>  $data['image'],
//        ]);
//        $url= $user->image;
        if ( $data['image']) {
            $this->success(__('请求成功'), ['status' =>  $data['image']]);
        } else {
            $this->error('请求失败');
        }
    }

//    /**
//     * 修改个人资料
//     * user_id
//     */
//    public function edituser(){
//
//        $request=request();
//
//        $data=$request->param();
//
//        if(empty($data) || is_numeric($data['mobile']))
//        $save=new BydDesigner();
//
//        $where['id']=$data['id'];
//
//        $edit=$save->isUpdate(true,$where)->save($data);
//
//        if($edit){
//
//            $this->success(__('修改成功'));
//
//        }else{
//
//            $this->error('修改失败');
//
//        }
//
//    }
/**
 * c端站内信通知
 * @param integer $user_id` '用户id',
 */
public function letter(){
    $data=$this->request->request('');
    if(empty($data['user_id']))$this->error('参数不正确');
    $arr=Bydletter::where('user_id',$data['user_id'])->order('id desc')->select();
    if(!empty($arr)){
        $this->success(__('请求成功'),['status'=>$arr]);
    }else{
        $this->error('暂无数据');
    }
}
/**
 * 活动通知
 */
public function activtz(){
    $data=$this->request->request('');
    if(empty($data['user_id']))$this->error('参数不正确');
    $user=\app\api\model\BydUser::find($data['user_id']);
    if(empty($user))$this->error('请登录');
    $arr=BydShopActivity::select();
    if(empty($arr))$this->error('暂无数据');
    $this->success(__('请求成功'),['status'=>$arr]);
}
/**
 * 获取用户formid
 */
public function  getformid(){
    $data=$this->request->request('');
    if(empty($data['user_id']) || empty($data['formid'])) $this->error('参数不全');
    $user=\app\admin\model\BydUser::find($data['user_id']);
    if(empty($user))$this->error('用户不存在');
    $time=time();
    $endtime=strtotime("+7days",$time);
    $add=new BydForm();
    $add->data([
        'userid'=>$data['user_id'],
        'formid'=>$data['formid'],
        'endtime'=>$endtime,
        'openid'=>$user['openid'],
    ]);
    $add->save();
    if($add){
        $this->success(__('请求成功'));
    }else{
        $this->error(__('请求失败'));
    }
}
/**
 * 获取用户手机号
 */
public function mobile(){
    $data=$this->request->request('');
    $phone=$this->checkMobile($data['mobile']);
    if($phone==false) $this->error(__('请输入正确的手机号'));
    if(empty($data['user_id']))$this->error(__('请登录'));
    $user=\app\admin\model\BydUser::find($data['user_id']);
    if(empty($user))$this->error(__('用户不存在'));

    $userphone=\app\admin\model\BydUser::where('id',$data['user_id'])->update(['mobile'=>$data['mobile']]);
    if($userphone){
        $this->success(__('请求成功'));
    }else{
        $this->error(__('服务器繁忙,请稍后再试'));
    }
}
    public function checkMobile($mobile)
    {
        return (preg_match('/^1((3|4|5|6|7|8|9){1}\d{1})\d{8}$/', $mobile) == 1) ? true : false;
    }
    public function qzqy(){
        $this->error(__('暂无数据'));
        $data=$this->request->request('');
        $find=BydUserAg::where('user_id',$data['user_id'])->where('qy',1)->find();

        if(empty($find)){
            $this->error(__('暂无数据'));
        }else{
           $agremnt=BydAgreement::where('id',$find['agid'])->find();
                $arrs=$agremnt['content'];
                $arrs=str_replace('{$star}','当前时间',$arrs);
                $arrs=str_replace('{$end}','明年截至时间',$arrs);
                $agremnt['content']=$arrs;

            $this->success(__('请求成功'),['status'=>$find]);
        }
    }
    public function timeout(){
        $this->error(__('暂无数据'));
        $data=$this->request->request('');
        $find=BydUserAg::where('user_id','=',$data['user_id'])->where('endtime','<',time())->order('id desc')->find();
        if(empty($find)){
            $this->error(__('暂无数据'));
        }else{
            $this->success(__('请求成功'),['status'=>$find]);
        }
    }
    /**
     * b2 b3签署是否提供服务
     * @param integer $users_id` '用户id',
     * @param integer $id` '订单id',
     */
    public function tgfw(){
        $data=$this->request->request('');
        if(empty($data['users_id']))$this->error(__('请登录'));
        $user=\app\api\model\BydUser::find($data['users_id']);
        if(empty($user))$this->error(__('用户信息错误'));
        if($user['bbs']==2){
            $find=Twotg::where('user_id',$data['users_id'])->where('order_id',$data['id'])->where('tx',1)->where('cl',0)->find();
            if(!empty($find)){
                $find['order']=BydShopOrder::where('id',$data['id'])->find();
                \think\Cache::set('fw',1,3600);
                if(time()>$find['endtime']){
                    $where['order_id']=['eq',$data['id']];
                    $where['user_id']=['neq',$data['users_id']];
                    $edit=Twotg::where($where)->update(['tx'=>1]);
                    $wheres['order_id']=['eq',$data['id']];
                    $wheres['user_id']=['eq',$data['users_id']];
                    $edit=Twotg::where($wheres)->update(['tx'=>0]);
                }
                $this->success(__('请求成功'),['status'=>$find]);
//                foreach ($find as &$v){
//                    if($v['endtime']>time()){
//                        $arr[]=$v;
//                    }else{
//
//                    }
//                }
//                if(empty($arr)) $this->error(__('暂无数据'));
//                $this->success(__('请求成功'),['status'=>$arr]);
            }else{
                $this->error(__('暂无数据'));
            }
        }elseif($user['bbs']==3){
            $find=Twotg::where('user_id',$data['users_id'])->where('order_id',$data['id'])->where('tx',1)->find();
            if(!empty($find)){
                $find['order']=BydShopOrder::where('id',$data['id'])->find();
                \think\Cache::set('fw',1,3600);
                $this->success(__('请求成功'),['status'=>$find]);
//                foreach ($find as &$v){
//                    if($v['endtime']>time()){
//
//                        $arr[]=$v;
//                    }else{
//                        $where['order_id']=['eq',$v['order_id']];
//                        $where['user_id']=['neq',$v['user_id']];
//                        $edit=Twotg::where($where)->update(['tx'=>1]);
//                    }
//                }
//                if(empty($arr)) $this->error(__('暂无数据'));
//                $this->success(__('请求成功'),['status'=>$arr]);
            }else{
                $this->error(__('暂无数据'));
            }
        }

        $this->error(__('暂无数据'));
    }
    /**
     * b2 b3 提供服务与否
     * @param integer $user_id` '用户id',
     * @param integer $id` '服务id',
     * @param integer $choice` '是否提供',
     */
    public function fwsure(){

        $data=$this->request->request('');

        $user=\app\api\model\BydUser::find($data['user_id']);
        $find=Twotg::where('id',$data['id'])->find();
        $findupda=Twotg::where('id',$data['id'])->update(['state'=>$data['choice'],'cl'=>1,'cztime'=>time()]);
       if($data['choice']==0){
           $wheres['id']=['eq',$find['order_id']];
           $findb=\app\admin\model\BydShopOrder::where($wheres)->find();
           if(empty($findb['three'])){
               $add=new \app\admin\model\Twotg();
               $add->data([
                   'user_id'=>1,
                   'order_id'=>$find['order_id'],
                   'level'=>3,
                   'endtime'=>'7962199200',
                   'tx'=>0,
                   'state'=>1
               ]);
               $add->save();
           }else{
               $userxq=\app\admin\model\BydUser::find($findb['three']);
               $arr=[
                   'openid'=>$userxq['openid'],
                   'thing2'=>"您有一个订单需要您提供服务",//$data['news'],
                   'thing6'=>"请前往小程序查看",
               ];
               $new=new News();
               $news=$new->vr($arr);
               $add=new \app\admin\model\Twotg();
               $add->data([
                   'user_id'=>$findb['three'],
                   'order_id'=>$find['id'],
                   'level'=>3,
                   'endtime'=>'7962199200',
                   'tx'=>0,
                   'state'=>1
               ]);
               $add->save();
               $order=\app\admin\model\BydShopOrder::where('id',$find['order_id'])->update(['threefw'=>1]);
               //$edit=\app\admin\model\Twotg::where($where)->update(['state'=>1]);
           }
       }
        if($findupda){
            $this->success(__('请求成功'));
        }else{
            $this->error(__('服务器繁忙,请稍后再试'));
        }
    }
    /**
     * b1申请楼盘
     * @param integer $user_id` '用户id',
     * @param integer $lpid` '楼盘id',
     */
    public function blp(){
        $data=$this->request->request('');
        if(empty($data['user_id']))$this->error(__('请登录'));
        $user=\app\admin\model\BydUser::find($data['user_id']);
        if(empty($user))$this->error(__('用户不存在'));
        if($user['bbs']!=1)$this->error(__('身份不符,无法申请'));
        if(empty($data['lpid']))$this->error(__('楼盘参数不正确'));
        $bulid=SoleBuilding::find($data['lpid']);
        if(empty($bulid))$this->error(__('楼盘参数不正确'));
        $quyu=BydDesignerArea::where('id',$bulid['area_id'])->find();
        $find=Apply::where('user_id',$data['user_id'])->where('lp',$data['lpid'])->where('state',0)->find();
        if(!empty($find))$this->error(__('申请成功'));
        $add=new Apply();
        $add->data([
            'user_id'=>$data['user_id'],
            'two'=>$bulid['sign_bid'],
            'three'=>$quyu['did'],
            'lp'=>$data['lpid'],
        ]);
        $add->save();
        if($add){
            $this->success(__('申请成功'));
        }else{
            $this->error(__('服务器繁忙,请稍后再试'));
        }
    }
    /**
     * 二维码进入小程序绑定
     * @param integer $user_id` '用户id',
     * @param integer $pid` '上级用户id',
     */
    public function ewmjoin(){
        $data=$this->request->request('');
        if(empty($data['user_id']))$this->error(__('请登录'));
        if(!empty($data['pid'])){

            //查找pid的身份信息
            $puser=\app\admin\model\BydUser::find($data['pid']);

            if($puser['bbs']>0){
                if($puser['bbs']==1){

                    //查找b1是否签约楼盘
                    $lpqy=Apply::where('user_id',$data['pid'])->where('state',0)->find();
                    if(!empty($lpqy)){

                    //b1建立临时关系
                    $find=Temrela::where('user_id',$data['user_id'])->where('pid',$data['pid'])->find();
                    if(empty($find)){
                        $add=new Temrela();
                        $add->data([
                            'user_id'=>$data['user_id'],
                            'pid'=>$data['pid'],
                            'two'=>$lpqy['two'],
                            'three'=>$lpqy['three'],
                            'level'=>1,
                        ]);
                        $add->save();
//                        if($add){
                            //添加成功后 接触其他的临时关系
                            $where['user_id']=['eq',$data['user_id']];
                            $where['pid']=['neq',$data['pid']];
//                            $findds=Temrela::where($where)->find();
//                            if(!empty($findds)){
                                $adds=Temrela::where($where)->update(['state'=>1,'close'=>1]);
//                            }
                        if($add){
                            $lpqys=Apply::where('user_id',$data['pid'])->order('id asc')->update(['state'=>1]);
                            $this->success(__('绑定成功'));
                        }else{
                            $this->error(__('服务器繁忙,请稍后再试'));
                        }
//                        }
                    }
                    }else{
                        $this->error(__('请申请楼盘'));
                    }
                }elseif($puser['bbs']==2){
                     $find=SoleBuilding::where('sign_bid',$puser['id'])->find();
                     if(empty($find)){
                         $three=0;
                     }else{
                         $btree=BydDesignerArea::where('id',$find['area_id'])->find();
                         $three=$btree['did'];
                     }
                    //b2建立临时关系
                    $find=Temrela::where('user_id',$data['user_id'])->where('two',$data['pid'])->find();
                    if(empty($find)){
                        $add=new Temrela();
                        $add->data([
                            'user_id'=>$data['user_id'],
                            'pid'=>0,
                            'two'=>$data['pid'],
                            'three'=>$three,
                            'level'=>2,
                        ]);
                        $add->save();

                            //添加成功后 接触其他的临时关系
                            $where['user_id']=['eq',$data['user_id']];
                            $where['two']=['neq',$data['pid']];
                            $findgx=Temrela::where($where)->update(['state'=>1,'close'=>1]);

                        if($add){
                            $this->success(__('绑定成功'));
                        }else{
                            $this->error(__('服务器繁忙,请稍后再试'));
                        }
                    }
                }elseif ($puser['bbs']==3){
                    //b3建立临时关系
                    $find=Temrela::where('user_id',$data['user_id'])->where('three',$data['pid'])->find();
                    if(empty($find)){
                        $add=new Temrela();
                        $add->data([
                            'user_id'=>$data['user_id'],
                            'pid'=>0,
                            'two'=>0,
                            'three'=>$data['pid'],
                            'level'=>3,
                        ]);
                        $add->save();

                            //添加成功后 接触其他的临时关系
                            $where['user_id']=['eq',$data['user_id']];
                            $where['three']=['neq',$data['pid']];
                            $findgx=Temrela::where($where)->update(['state'=>1,'close'=>1]);

                        if($add){
                            $this->success(__('绑定成功'));
                        }else{
                            $this->error(__('服务器繁忙,请稍后再试'));
                        }
                    }
                }

            }else{
                $this->success(__('请求成功'));
            }
        }else{
            $this->error(__('上级不能为空'));
        }
    }
}